
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.system.filter.role import RoleFilter
from apps.system.models import User, Role, Permission
from apps.system.serializers.role import RoleSerializer
from apps.utils.menu import tree_menu


class RoleView(ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer

    # 自定义搜索
    filterset_class = RoleFilter



    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()

        serializer = self.get_serializer(instance)
        data = serializer.data
        # data['list'] = User.objects.filter(is_delete=False, is_active=True).values('id', 'username')
        # print(request.user.id)
        return Response(data, status=status.HTTP_200_OK)

    @action(methods=['GET'], detail=True, name='permission', url_name='role_permission')
    def permission(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)

        permission_fields = ['id', 'name']
        permission = Permission.objects.filter(is_active=True).values(*permission_fields)
        data = {
            'items': tree_menu(permission),
            'role': {
                'id': serializer.data['id'],
                'name': serializer.data['name'],
                'permissions': serializer.data['permissions'].split(',')
            },
        }

        return Response(data, status=status.HTTP_200_OK)


class RoleListView(APIView):
    """
    添加角色等用此接口读取后台账号列表
    """
    # 去除掉全局的rbac访问权限
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        name = request.data.get('name')

        condition = {'is_active': True}

        if name:
            condition['name__contains'] = name

        roles = Role.objects.filter(**condition).values('id', 'name')
        return Response(roles, status=status.HTTP_200_OK)
